/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package etherblocks.engine.network;

import java.net.DatagramSocket;
import java.net.ServerSocket;

/**
 *
 * @author Carl
 */
public class NetworkUtil{
    
    public static NetworkConnectionSettings getConnectionSettings_HostOrConnectLocal(int port){
        NetworkConnectionSettings connectionSettings;
        if(isPortAvailable(port)){
            connectionSettings = new NetworkConnectionSettings(NetworkConnectionSettings.UserType.SERVER, port);
        }
        else{
            connectionSettings = new NetworkConnectionSettings(NetworkConnectionSettings.UserType.CLIENT, port);
            connectionSettings.setHost("localhost");
        }
        return connectionSettings;
    }

    public static boolean isPortAvailable(int port){
        ServerSocket ss = null;
        DatagramSocket ds = null;
        try{
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        }catch(Exception ex){
        }finally{
            if(ds != null){
                ds.close();
            }
            if(ss != null){
                try{
                    ss.close();
                }catch (Exception ex){
                }
            }
        }
        return false;
    }
}
